/*
 * @lc app=leetcode.cn id=890 lang=typescript
 *
 * [890] 查找和替换模式
 */

// @lc code=start
function findAndReplacePattern(words: string[], pattern: string): string[] {
  const n = words.length;
  const matchWord = (w1: string, w2: string): boolean => {
    const map = new Map<string, string>();
    for (let i = 0; i < w1.length; i++) {
      const x = w1[i];
      const y = w2[i];
      if (!map.has(x)) {
        map.set(x, y);
      } else if (map.get(x) !== y) {
        return false;
      }
    }
    return true;
  };

  const ans: string[] = [];
  for (let i = 0; i < n; i++) {
    if (matchWord(words[i], pattern) && matchWord(pattern, words[i])) {
      ans.push(words[i]);
    }
  }

  return ans;
}
// @lc code=end
